package com.zjj.lbw.designpattern.singleton;

import java.io.*;

/**
 * @author zhanglei.zjj
 * @description 以静态内部类实现懒汉单例模式为例探讨序列化对打破单例的影响
 * @date 2023/7/11 21:59
 */
public class InnerClassSingletonSerializableTest {
    public static void main(String[] args) throws IOException {
        InnerClassSingleton instance = InnerClassSingleton.getInstance();

        // 序列化
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("java-design-pattern/src/main/resources/instance"))) {
            oos.writeObject(instance);
        }

        // 反序列化
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("java-design-pattern/src/main/resources/instance"))) {
            InnerClassSingleton innerClassSingleton = (InnerClassSingleton) ois.readObject();

            System.out.println(innerClassSingleton == instance);

        } catch (ClassNotFoundException | FileNotFoundException e) {
            e.printStackTrace();
        }

    }
}

class InnerClassSingleton implements Serializable {
//    private static final long serialVersionUID = 6922639953390195232L;

    static {
        System.out.println(" InnerClassSingleton "); //  1
    }

    private InnerClassSingleton() {

        if (SingletonHolder.instance != null) {
            throw new RuntimeException(" 不允许多个实例。");
        }

    }

    public static InnerClassSingleton getInstance() {
        return SingletonHolder.instance;
    }

    Object readResolve() throws ObjectStreamException {
        return SingletonHolder.instance;
    }

    private static class SingletonHolder {
        private static InnerClassSingleton instance = new InnerClassSingleton();

        static {
            System.out.println(" SingletonHolder ");// 2
        }
    }

    // 用来控制 序列化后 类发生改变
//    private float f = 0.0f;
}